
import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';


import { File } from '../models/File';

@Injectable()
export class FileService {

    private baseUrl =  'api/file';

    constructor(
        private http: HttpClient
    ) {
    }



    getFiles(): Observable<File[]> {
        return this.http.get<File[]>(this.baseUrl);
    }



    getFile(id: string): Observable<File> {
        return this.http.get<File>(`${this.baseUrl}/${id}`);
    }



    update(file: File): Observable<File> {
        const headers = new HttpHeaders({'Content-Type': 'application/json'});
        const url = `${this.baseUrl}/${file.id}`;
        return this.http
            .put<File>(url, JSON.stringify(file), {headers: headers});
    }

    create(name: string): Observable<File> {
        const headers = new HttpHeaders({'Content-Type': 'application/json'});
        return this.http
            .post<File>(this.baseUrl, JSON.stringify({name: name}), {headers: headers});
    }

    del(id: number): Observable<any> {
        const url = `${this.baseUrl}/${id}`;
        const headers = new HttpHeaders({'Content-Type': 'application/json'});
        return this.http.delete(url, {headers: headers});
    }

    delAllByIds(ids: string[]): Observable<any> {
        const url = `${this.baseUrl}/delete`;
        let params: HttpParams = new HttpParams().append('where', JSON.stringify({id: {$in: ids}}));
        const headers = new HttpHeaders({'Content-Type': 'application/json'});
        return this.http.delete(url, {headers: headers, params: params});
    }

    delEditorFileBySrc(src: string): Observable<any> {
        const url = `api/editor${src.substring(src.indexOf('/'))}`;
        return this.http.delete(url);
    }

}
